<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-7-26
 * Time: 下午6:53
 */

class Index{

  static function main(){
    date_default_timezone_set("PRC");
    error_reporting(E_ALL);
    @ini_set("display_errors","Off");
    function exception_error_handler($errno,$errstr,$errfile,$errline){
      throw new ErrorException($errstr,0,$errno,$errfile,$errline);
    }
    set_error_handler("exception_error_handler");

    spl_autoload_register(function ($class){
      $class = str_replace("\\","/",$class);
      $class = explode("/",$class);
      $endClass = array_pop($class);
      foreach ($class as $key => $item){
        $class[$key] = strtolower($item);
      }

      $class[] = $endClass;
      $class = implode("/",$class);
      if (file_exists($class.'.inc')){
        require_once $class.'.inc';
      }
    });
    //----ProjectInit init -----//
    ProjectInit::init();
    foreach (ProjectInit::$objects as $object){
      if (file_exists($object)){
        require_once $object;
      }
    }
    //----ProjectInit init -----//
    try{
      $request = new \Tiny\Request();
      $response = new \Tiny\Response();

      $request->data = file_get_contents("php://input");
      $request->api = $_SERVER['REQUEST_URI'];
      $request->httpHeaders = $_SERVER;
      $request->uid = "";


      $api = str_replace("/","\\",$request->api);
      if (!class_exists($api)){
        $response->httpStatus = \Tiny\HttpStatus::NOT_FOUND;
        $response->httpStatusMsg = "Api Not Found";
      }else{
        /**
         * @var $api \Tiny\API
         */
        $api = new $api;
        $api->process($request,$response);
      }
    }catch (Exception $e){
      $response->httpStatus = \Tiny\HttpStatus::FAILED;
      $response->httpStatusMsg = "php run error";
      \Tiny\Logger::getInstance()->trace($e->getMessage());
    }


    if ($response->httpStatus != \Tiny\HttpStatus::SUC){
      header("HTTP/1.1 ".$response->httpStatus." ".$response->httpStatusMsg);
      return ;
    }
    //httpheaders
    foreach ($response->httpHeaders as $header => $value){
      header($header.":".$value);
    }
    if (!empty($response->data)){
      file_put_contents("php://output",$response->data);
    }
  }
}
Index::main();